package club.dmyang.service;

import club.dmyang.dao.FriendShipLinkMapper;
import club.dmyang.entity.FriendShipLink;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by brss on 2018/8/14.
 */
@Service("friendshipLinkService")
public class FriendshipLinkServiceImpl implements FriendshipLinkService {

    @Autowired
    private FriendShipLinkMapper friendShipLinkMapper;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;


    /**
     * 根据sort升序获取所有 友情链接 记录
     *
     * @return
     */
    @Override
    public List<FriendShipLink> listAll() {
        //从缓存中读
        try {
            String allLinks = redisTemplate.opsForValue().get("friendshipLink_listAll");
            if ( allLinks != null ){
                List<FriendShipLink> friendShipLinks = JSON.parseArray(allLinks, FriendShipLink.class);
                return friendShipLinks;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        List<FriendShipLink> dbFriendShipLinks = friendShipLinkMapper.selectAll();

        try {
            String sLinks = JSON.toJSONString(dbFriendShipLinks);
            //写缓存
            redisTemplate.opsForValue().set("friendshipLink_listAll",sLinks);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return dbFriendShipLinks;
    }
}
